package com.tjetc.util.file;

import com.tjetc.util.Utils;
import com.tjetc.util.config.MinioConfig;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

@Service
public class FileService {
    @Autowired
    private MinioClient minioClient;
    @Autowired
    private MinioConfig minioConfig;

    //将文件传递到minio中 并且返回文件绝对路径
    public String uploadFile(MultipartFile file) throws IOException, ServerException, InsufficientDataException, ErrorResponseException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        //修改文件名
        System.out.println("文件名:"+file.getOriginalFilename());
        String fileName = Utils.extractFileName(file.getOriginalFilename());
        //上传minio
        InputStream inputStream = file.getInputStream();
        //构建上传参数
        PutObjectArgs args = PutObjectArgs.builder()
                .bucket(minioConfig.getBucketName())//设置桶名称
                .object(fileName)//上传文件名称
                .stream(inputStream, file.getSize(), -1)//上传文件
                .contentType(file.getContentType())
                .build();
        minioClient.putObject(args);
        //拼接绝对路径 返回
        String url = minioConfig.getUrl() + "/" +
                minioConfig.getBucketName() + "/" + fileName;
        return url;
    }
}
